import 'dart:convert';
import 'dart:io';
import 'dart:math';

import 'package:dotted_border/dotted_border.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:insta_image_viewer/insta_image_viewer.dart';
import 'package:school_assistant/common_colors.dart';
import 'package:school_assistant/toast_utils.dart';
import 'package:school_assistant/user_feedback_imgs.dart';
import 'package:sp_util/sp_util.dart';

import 'common_client.dart';
import 'common_utils.dart';
import 'data/article_entity.dart';
import 'data/article_extra_entity.dart';
import 'data/base_data_entity.dart';
import 'data/goods_moni.dart';
import 'data/shiwu_entity.dart';

class ShiwuAddPage extends StatefulWidget {
  ShiwuAddPage(this.ty, {Key? key}) : super(key: key);
  int ty = 1;

  @override
  State<ShiwuAddPage> createState() => _ShiwuAddPageState();
}

class _ShiwuAddPageState extends State<ShiwuAddPage> {
  List<XFile> imgFeed = [];
  final _controllerTitle = TextEditingController();
  final _controllerContent = TextEditingController();
  final _controllerPhone = TextEditingController();
  final _controllerAddress = TextEditingController();

  @override
  void dispose() {
    super.dispose();
    _controllerTitle.dispose();
    _controllerContent.dispose();
    _controllerPhone.dispose();
    _controllerAddress.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfff5f5f5),
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          onPressed: () => Get.back(),
          icon: Icon(
            Icons.arrow_back_ios,
            color: Colors.black,
          ),
        ),
        centerTitle: true,
        title: Text(
          widget.ty == 1 ? "寻物启事" : "失物招领",
          style: TextStyle(
              fontSize: 18, color: Colors.black, fontWeight: FontWeight.w600),
        ),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Flexible(
              child: Container(
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: BorderRadius.circular(4)),
            margin: EdgeInsets.all(12),
            padding: EdgeInsets.all(12),
            child: ListView(
              children: [
                Text(
                  "标题",
                  style: TextStyle(color: Color(0xff333333), fontSize: 16),
                ),
                SizedBox(
                  height: 8,
                ),
                TextField(
                  maxLength: 30,
                  controller: _controllerTitle,
                  maxLines: 1,
                  decoration: InputDecoration(
                      hintText: '请输入标题',
                      filled: true,
                      border: InputBorder.none,
                      fillColor: Color(0XFFF1F1F1)),
                ),
                Text(
                  "正文",
                  style: TextStyle(color: Color(0xff333333), fontSize: 16),
                ),
                SizedBox(
                  height: 8,
                ),
                TextField(
                  maxLength: 140,
                  maxLines: 4,
                  controller: _controllerContent,
                  decoration: InputDecoration(
                      hintText: '请输入正文',
                      filled: true,
                      border: InputBorder.none,
                      fillColor: Color(0XFFF1F1F1)),
                ),
                Text(
                  "联系方式",
                  style: TextStyle(color: Color(0xff333333), fontSize: 16),
                ),
                SizedBox(
                  height: 8,
                ),
                TextField(
                  maxLines: 1,
                  maxLength: 13,
                  controller: _controllerPhone,
                  inputFormatters: [
                    //限制只允许输入数字
                    FilteringTextInputFormatter.digitsOnly,
                    // //限制输入长度不超过11位
                    LengthLimitingTextInputFormatter(11),
                  ],
                  keyboardType: TextInputType.number,
                  decoration: InputDecoration(
                      counterText: "",
                      hintText: '请输入联系方式',
                      filled: true,
                      border: InputBorder.none,
                      fillColor: Color(0XFFF1F1F1)),
                ),
                SizedBox(
                  height: 10,
                ),
                Text(
                  "图片",
                  style: TextStyle(color: Color(0xff333333), fontSize: 16),
                ),
                SizedBox(
                  height: 8,
                ),
                GridView.builder(
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 4,
                    childAspectRatio: 1,
                  ),
                  itemCount: imgFeed.length < 3 ? imgFeed.length + 1 : 3,
                  itemBuilder: (context, index) {
                    //   return Image.file(File(imgAD[index].path));
                    return index < imgFeed.length
                        ? _singleAD(index)
                        : _imgAdd(index);
                  },
                )
              ],
            ),
          )),
          GestureDetector(
            onTap: () {
              // print(DateTime.now().toLocal().toString().substring(0,19));
              _postArticle();
            },
            child: Container(
              alignment: Alignment.center,
              margin: EdgeInsets.only(left: 12, right: 12, bottom: 10),
              height: 50,
              decoration: BoxDecoration(
                  color: widget.ty == 1
                      ? CommonColor.colorMainGreen
                      : CommonColor.colorMainBlue,
                  borderRadius: BorderRadius.circular(4)),
              child: Text(
                "发布",
                style: TextStyle(
                    color: Color(0XFF333333),
                    fontSize: 18,
                    fontWeight: FontWeight.w600),
              ),
            ),
          )
        ],
      ),
    );
  }

  _postArticle() async {
    try {
      if (_controllerTitle.text.isEmpty) {
        return QmToast.toast('请输入标题!');
      }
      if (_controllerContent.text.isEmpty) {
        return QmToast.toast('请输入内容!');
      }
      // if (_controllerPhone.text.isEmpty) {
      //   return QmToast.toast('请输入联系方式!');
      // }
      // if (imgFeed.isEmpty) {
      //   return QmToast.toast('请至少传一张图!');
      // }

      EasyLoading.show(status: 'loading...');
      List<String> urls = [];
      if (imgFeed.isNotEmpty) {
        for (var element in imgFeed) {
          await _uploadImg(element).then((value) => urls.add(value));
        }
      }
      var shiwu = ShiwuEntity();
      shiwu.id = Random().nextInt(99999);
      shiwu.ty = widget.ty;
      shiwu.title = _controllerTitle.text;
      shiwu.content = _controllerContent.text;
      shiwu.img = jsonEncode(urls);
      shiwu.tel = _controllerPhone.text;
      shiwu.time = QUtils.nowTimeStr();
      shiwu.name = QUtils.getName();
      shiwu.profile = UserFeedBackImgs.url + QUtils.getProfile();
      List<dynamic> data = jsonDecode(Moni.getShiwu());
      List<ShiwuEntity> gs = [];
      if (data != null) {
        data.forEach((element) {
          gs.add(ShiwuEntity.fromJson(element));
        });
      }
      gs.add(shiwu);
      SpUtil.putString("shiwu", jsonEncode(gs));
    } catch (e) {
      print(e);
    } finally {
      EasyLoading.dismiss();
      Get.back(result: true);
    }
  }

  _singleAD(int pos) {
    return Stack(
      children: [
        Positioned(
          right: 6,
          top: 6,
          child: InstaImageViewer(
            child: Image.file(
              File(imgFeed[pos].path),
              width: 68,
              height: 68,
              fit: BoxFit.cover,
              alignment: Alignment.topCenter,
            ),
          ),
        ),
        Positioned(
          right: 0,
          child: GestureDetector(
              onTap: () {
                imgFeed.removeAt(pos);
                setState(() {});
              },
              child: Image.asset(
                UserFeedBackImgs.user_feedback_del,
                width: 18,
              )),
        )
      ],
    );
  }

  _imgAdd(int pos) {
    return Stack(
      children: [
        Positioned(
            right: 6,
            top: 6,
            left: 5,
            bottom: 5,
            child: GestureDetector(
              onTap: () => getLostData(pos),
              child: DottedBorder(
                color: Color(0xffE3E3E3),
                strokeWidth: 1,
                radius: const Radius.circular(4),
                child: Center(
                  child: RichText(
                      textAlign: TextAlign.center,
                      text: TextSpan(children: [
                        WidgetSpan(
                            child: Image.asset(
                          UserFeedBackImgs.user_feedback_camare,
                          width: 14,
                        )),
                        const TextSpan(
                          text: '\n',
                        ),
                        TextSpan(
                            text: "上传图片",
                            style: TextStyle(
                                color: Color(0xff999999),
                                fontSize: 9,
                                height: 2))
                      ])),
                ),
              ),
            ))
      ],
    );
  }

  Future<String> _uploadImg(XFile locFile) async {
    var file = File(locFile.path);
    BaseDataEntity model = await CommonClient().commonUpFile(file);
    if (model.status == true) {
      return model.data ?? '';
    } else {
      return '';
    }
  }

  getLostData(int pos) async {
    if (imgFeed.length >= 3) {
      QmToast.toast("最多选3张图片");
      return;
    }
    final ImagePicker picker = ImagePicker();
    final XFile? image =
        await picker.pickImage(source: ImageSource.gallery, imageQuality: 70);
    if (image != null) imgFeed.insert(pos, image);
    setState(() {});
  }
}
